package org.example;

import java.util.Objects;

/**
 * 14. 最长公共前缀
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 *
 *  
 *
 * 示例 1：
 *
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 * 示例 2：
 *
 * 输入：strs = ["dog","racecar","car"]
 * 输出：""
 * 解释：输入不存在公共前缀。
 *  
 *
 * 提示：
 *
 * 0 <= strs.length <= 200
 * 0 <= strs[i].length <= 200
 * strs[i] 仅由小写英文字母组成
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/longest-common-prefix
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class LongestCommonPrefixSolution {

    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        int minLen = getMinLen(strs);
        int index = 0;
        while (index < minLen) {
            Character cur = null;
            Boolean add = true;
            for (String str : strs) {
                if (cur == null) {
                    cur = str.charAt(index);
                    continue;
                }
                char next = str.charAt(index);
                if (!Objects.equals(next, cur)) {
                    add = false;
                }
            }
            if (add) {
                sb.append(cur);
                index ++;
                continue;
            }
            break;
        }
        return sb.toString();
    }

    private int getMinLen(String[] strs) {
        Integer minLen = null;
        for (String str : strs) {
            int cur = str.length();
            if (minLen == null) {
                minLen = cur;
                continue;
            }
            if (minLen > cur) {
                minLen = cur;
            }
        }
        return minLen == null ? 0 : minLen;
    }

    public static void main(String[] args) {
        String[] strs = {"flower","flow","flight"};
        LongestCommonPrefixSolution solution = new LongestCommonPrefixSolution();
        System.out.println(solution.longestCommonPrefix(strs));
    }
}
